import { CSLineSegments, CSMesh, IShapeData } from '@amcax/base';
import { dataManager } from '@app-base/module';
import { Object3D } from 'three-legacy';

/**
 * 根据提供的面id数组，获取这些面所包含的边id数组（id不重复）
 * @param facesId 面id数组
 * @returns 边id数组
 */
const getLinesIdOfFaces = (facesId: string[]) => {
  const linesId: Set<string> = new Set();
  facesId?.forEach((faceId: string) => {
    // faceId=dxid:f[index]，比如：dxid:f0
    const dxid = faceId?.split(':')?.[0];
    if (!dxid) {
      return;
    }
    const faceIndex = Number(faceId.split(':')[1].slice(1));
    const shapeData = dataManager.getShapeData(dxid) as IShapeData;
    const face = shapeData.faces[faceIndex];
    face.edges.forEach((edge) => {
      linesId.add(`${dxid}:e${edge}`);
    });
  });
  return Array.from(linesId);
};

/**
 * 从指定的group中找到modelDxid的模型
 * @param group
 * @param modelDxid
 * @returns 找到返回对应的模型,没找到则返回null
 */
const findModelInGroup = (group: Object3D, modelDxid: string) => {
  for (let i = 0, l = group?.children?.length; i < l; i++) {
    const o = group.children[i];
    if (o instanceof CSLineSegments || o instanceof CSMesh) {
      if (o.modelDxid === modelDxid) {
        return o;
      }
    }
  }
  return null;
};
export { findModelInGroup, getLinesIdOfFaces };
